import { Button, Form, Input, Radio, Select,} from "antd";
import {Link, useLocation, Outlet, useNavigate} from "react-router-dom";
// import "./Help.css";
import {useEffect, useState} from "react";
import axios from "axios";

const {Option} = Select;
// eslint-disable-next-line react-hooks/rules-of-hooks





export default function Register(){
    const [name, setName] = useState(''); // 用户名
    const [user, setUser] = useState(''); // 账号
    const [password, setPassword] = useState('');   // 密码1
    const [email, setEmail] = useState(''); //邮箱
    const [dbinfos, setdbinfos] = useState([]);   // 从数据库获取的信息
    const [name_state, setNameState] = useState(true);
    const [user_state, setUserState] = useState(true);
    const [form] = Form.useForm();
    const navigate = useNavigate();  // 只能在组件中使用
    const formItemLayout = {
        labelCol: {
            span: 4,
        },
        wrapperCol: {
            span: 14,
        },
    };
    const buttonItemLayout = {
        wrapperCol: {
            span: 14,
            offset: 4,
        },
    };

    function handleChangeName(e) {
        let names = dbinfos.map( item => item.name);  // 使用名字构建一个数组
        let name = e.target.value;
        console.log(names, name);
        if(names.includes(name) === true) {  // 如果在里面
            alert("用户名重复！");
            setNameState(false)
        } else {
            setName(name);
        }
    }


    function handleChangeUser(e){
        let users = dbinfos.map( item => item.user);  // 使用名字构建一个数组
        let user = e.target.value;
        console.log(users, user);
        if(users.includes(user) === true) {  // 如果在里面
            alert("账号重复！");
            setUserState(false)
        } else {
            setUser(user);
        }
    }

    function handleChangePassword(e) {
        setPassword(e.target.value);
    }

    function handleChangeEmail(e){
        setEmail(e.target.value);
    }
    function onFinish() {
        console.log(name, user, password, email);
    }

    // 首次启动的时候，调用该方法，获取
    useEffect(() => {
        axios.get('/api/getInfos')
            .then((data) => {
                console.log(data)
                console.log(data['data']['data']);
                setdbinfos(data["data"]['data'])   // 设置传入进来的db值
            })
    },[])  // 刚开始的运行该组件的时候调用即可。

    function onFinish() {
        let data = {
            user: user,
            name: name,
            password: password,
            email: email
        }
        axios.post('/api/register', data)
            .then( res => {
                console.log(res);
                if( res.data.status === 200 ){
                    alert("注册成功。");
                    navigate('/');
                } else {
                    alert("注册失败。");
            }
        })
    }
    return(
        <Form
            {...formItemLayout}
            layout={'horizontal'}
            form={form}
            initialValues={{
                layout: 'horizontal',
            }}
            onFinish={onFinish}
        >
            <Form.Item label="用户名">
                <Input placeholder="显示的名字" onChange={handleChangeName} required={true}/>
            </Form.Item>
            <Form.Item label="账号">
                <Input placeholder="登录时使用的账户" onChange={handleChangeUser} required={true}/>
            </Form.Item>
            <Form.Item
                name="password"
                label="密码"
                rules={[
                    {
                        required: true,
                        message: 'Please input your password!',
                    },
                ]}
                hasFeedback
            >
                <Input.Password onChange={handleChangePassword}/>
            </Form.Item>

            <Form.Item
                name="confirm"
                label="确认密码"
                dependencies={['password']}
                hasFeedback
                rules={[
                    {
                        required: true,
                        message: '请确认你的密码',
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();   // 返回Promise，这个是异步的，异步拒绝该请求
                            }
                            return Promise.reject(new Error('两次密码不匹配'));
                        },
                    }),
                ]}
            >
                <Input.Password />
            </Form.Item>
            <Form.Item label="E-mail" required={true} name="email" rules={[
                {
                    type: 'email',
                    message:'邮箱格式有误'
                },
                {
                    require: true,
                    message: "输入邮箱"
                }
            ]}>
                <Input onChange={handleChangeEmail}/>
            </Form.Item>
            <Form.Item {...buttonItemLayout}>
                <Button type="primary" htmlType="submit">注 册</Button>
            </Form.Item>
        </Form>
    )
}